package
{
	import Item.CItem;
	import Item.CItemManager;
	
	import Snake.CSnake;
	import Snake.CSnakePiece;
	
	import srdk.SRAABB;
	
	public class CCollisionManager
	{
		private var m_refSnake :CSnake;
		private var m_refItemManager :CItemManager;
		
		public function CCollisionManager(refSnake :CSnake, refItemManager :CItemManager)
		{
			m_refSnake = refSnake;
			m_refItemManager = refItemManager;
		}
		public function Update() :void
		{
			ProcessCollision_SnakeHead_Item();
			ProcessCollision_SnakePieses();
		}
		private function ProcessCollision_SnakeHead_Item() :void
		{
			var refHeadPiece :CSnakePiece = m_refSnake.GetBodyPiece(0);
			if (refHeadPiece != null)
			{
				var refItem :CItem = null;
				var count :uint = m_refItemManager.count;
				for (var i :uint = 0; i < count; ++i)
				{
					refItem = m_refItemManager.GetItem(i);
					
					var dx :Number = (refHeadPiece.aabb.width/2 + refItem.aabb.width/2);
					var dy :Number = (refHeadPiece.aabb.height/2 + refItem.aabb.height/2);
					if (Math.abs(refHeadPiece.aabb.x - refItem.aabb.x) < dx &&
						Math.abs(refHeadPiece.aabb.y - refItem.aabb.y) < dy)
					{
						if (m_refSnake.ProcessCollision_Item(refItem) == true)
						{
							m_refItemManager.DeleteItem(i);
						}
						return;
					}
				}
			}
		}
		private function ProcessCollision_SnakePieses() :void
		{
			var refHeadPiece :CSnakePiece = m_refSnake.GetBodyPiece(0);
			if (refHeadPiece != null)
			{
				var aabbHeadDest :SRAABB = new SRAABB;
				aabbHeadDest.Init(refHeadPiece.nDestPositionX, refHeadPiece.nDestPositionY, refHeadPiece.aabb.width, refHeadPiece.aabb.height);
			
				var refSnakePiece :CSnakePiece = null;
				var count :uint = m_refSnake.nBodyPieceCount;
				for (var i :uint = 1; i < count; ++i)
				{
					refSnakePiece = m_refSnake.GetBodyPiece(i);
					
					var dx :Number = (aabbHeadDest.width/2 + refSnakePiece.aabb.width/2);
					var dy :Number = (aabbHeadDest.height/2 + refSnakePiece.aabb.height/2);
					if (Math.abs(aabbHeadDest.x - refSnakePiece.aabb.x) < dx &&
						Math.abs(aabbHeadDest.y - refSnakePiece.aabb.y) < dy)
					{
						m_refSnake.ProcessCollision_BodyPiece(i);
						return;
					}
				}
			}
		}
		
	}
}